package handle

import (
	"net/http"
	"os"
	"path/filepath"

	"github.com/gin-gonic/gin"
)

// 文件列表API
func ListBackupFiles(backupDir string, c *gin.Context) {
	files, err := os.ReadDir(backupDir)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	var fileList []string
	for _, file := range files {
		if !file.IsDir() {
			fileList = append(fileList, file.Name())
		}
	}

	c.JSON(http.StatusOK, gin.H{"files": fileList})
}

// 文件下载API
func DownloadBackupFile(backupDir string, c *gin.Context) {
	filename := c.Param("filename")
	filePath := filepath.Join(backupDir, filename)

	// 安全检查，防止目录遍历
	if !filepath.IsAbs(filePath) {
		filePath = filepath.Clean(filepath.Join(backupDir, filename))
		backupDirAbs, _ := filepath.Abs(backupDir)
		filePathAbs, _ := filepath.Abs(filePath)

		// 检查文件是否在备份目录内
		if len(filePathAbs) <= len(backupDirAbs) || filePathAbs[:len(backupDirAbs)] != backupDirAbs {
			c.JSON(http.StatusBadRequest, gin.H{"error": "无效的文件路径"})
			return
		}
	}

	// 检查文件是否存在
	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		c.JSON(http.StatusNotFound, gin.H{"error": "文件不存在"})
		return
	}

	// 提供文件下载
	c.File(filePath)
}
